package com.dgut.service.background.controller;

import com.alibaba.fastjson.JSON;
import com.dgut.service.background.config.resultConfig.JsonResult;
import com.dgut.service.background.config.resultConfig.ResultTool;
import com.dgut.service.background.service.PassService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 出入统计
 */
@RestController
@RequestMapping("pass")
public class PassController {
    @Autowired
    private PassService passService;

    //出入信息临时对象
    @Data
    class Pass{
        int[] outsData; //出门次数
        int[] enterData; //进门次数
        String[] dayData; //日期
        public Pass(int[] enterData, int[] outsData, String[] dayData){
            this.enterData = enterData;
            this.outsData = outsData;
            this.dayData = dayData;
        }
    }

    //按时间范围获取出入信息
    @GetMapping("passData/{days}")
    public String getPassData(@PathVariable("days") int days){
        int[] outsData = new int[days];
        int[] enterData = new int[days];
        String[] dayData = new String[days];
        days--;
        Date date1;
        Date date2;
        String date1String;
        String date2String;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        date2 = new Date();
        date1 = getFrontDay(date2);
        //前一天时间
        date1String = format.format(date1);
        //今天时间
        date2String = format.format(date2);
        for(int i = days; i >= 0; i--){
            enterData[i] = passService.getEnterData(date1String, date2String);
            outsData[i] = passService.getOutsData(date1String, date2String);
            SimpleDateFormat newFormat = new SimpleDateFormat("MM-dd");
            String newDate1String = newFormat.format(date1);
            dayData[i] = newDate1String;
            if (i == 0)break;
            date2 = date1;
            date1 = getFrontDay(date2);
            date1String = format.format(date1);
            date2String = format.format(date2);
        }
        Pass pass = new Pass(enterData, outsData, dayData);
        JsonResult result = ResultTool.success(pass);
        return JSON.toJSONString(result);
    }

    private Date getFrontDay(Date today){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.add(calendar.DATE, -1);
        return calendar.getTime();
    }
}
